package com.anc.web.aop;


import constants.CommonConstants;
import enums.BaseRespCodeEnum;
import exception.AncException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import util.JsonUtil;

/**
 * @Desciption:
 * @author: Anc
 * @date: 2022/7/01
 */
@Aspect
@Slf4j
@Component
public class RemoteExceptionWrapAdvice {
    @Around("@within(com.anc.web.annotions.RemoteService)")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        String methodName = methodSignature.getMethod()
            .getName();
        //获取参数名字
        Object[] args = joinPoint.getArgs();
        StringBuilder argsDump = new StringBuilder();
        Object retVal = null;
        try {
            if (args != null && args.length > 0) {
                for (int i = 0; i < args.length; i++) {
                    Object obj = args[i];
                    argsDump.append(null == obj ? "null" : JsonUtil.toJSon(obj))
                        .append(",");
                }
            }
            retVal = joinPoint.proceed();
        } catch (Exception e) {
            log.error("Occur exception,class:{}, method:{}, args:{}, {} msg:{}",
                methodSignature.getDeclaringTypeName(), methodName, argsDump, CommonConstants
                    .LINE_SEP, ExceptionUtils.getStackTrace(e));
            //业务异常直接抛出
            if (e instanceof AncException) {
                throw e;
            }
            //非业务异常包一层
            throw new AncException(BaseRespCodeEnum.REMOTE_THIRD_EXCEPTION, e);
        }
        return retVal;
    }
}
